﻿using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using Daq.Models;
using Daq.Utils;
using Daq.ViewModels;
using Daq.Views;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.SplashScreen;
using Telerik.Windows.Documents.Spreadsheet.Expressions.Functions;
using CommunityToolkit.Mvvm.ComponentModel;
using Daq.Services;
namespace Daq
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RadRibbonWindow, IRecipient<DesktopAlertMessage>
    {
		private RadRibbonWindow parentWindow;
		private DispatcherTimer timer;
		private static Random random = new Random();
		private SplashScreenDataContext splashScreenDataContext;
		private readonly DeviceService? deviceService;
		public MainWindow()
		{
			InitializeComponent();
            //var culture = new CultureInfo("zh-CN");
            //var dtfInfo = new DateTimeFormatInfo
            //{
            //	ShortDatePattern = "yyyy年M月d日",
            //	ShortTimePattern = "HH:mm",
            //	DateSeparator = "-"
            //};
            //culture.DateTimeFormat = dtfInfo;
            //Thread.CurrentThread.CurrentCulture = culture;
            //Thread.CurrentThread.CurrentUICulture = culture;

            //ribbonTabHome.DataContext = App.Current.Services.GetService<DaqViewModel>();
            ribbonTabData.DataContext = App.Current.Services.GetService<DataManagerViewModel>();

			this.deviceService = App.Current.Services.GetService<DeviceService>();
			if(deviceService != null)
			{
                ribbonTabHome.DataContext = deviceService;
				ribbonTabSettings.DataContext = deviceService;
            }
			statusBar.DataContext = App.Current.Services.GetService<DaqViewModel>();
            //         this.timer = new DispatcherTimer();
            //this.timer.Interval = TimeSpan.FromMilliseconds(10);
            //this.timer.Tick += OnTimerTick;


            //Task.Run(() =>
            //{
            //	bool visible = true;
            //	while (true)
            //	{
            //		App.Current.Dispatcher.Invoke(() =>
            //		{
            //			txtBlockWarning.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
            //		});

            //		Thread.Sleep(200);
            //		visible = !visible;

            //	}
            //});

            WeakReferenceMessenger.Default.Register<DesktopAlertMessage>(this);
            
        }


		private void OnTimerTick(object sender, EventArgs e)
		{
			if (this.splashScreenDataContext.ProgressValue < 100)
			{
				this.UpdateProgress();
			}
			else
			{
				this.CloseSplashScreen();
			}
		}

		private void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			//if (!LicenseHelper.CheckLicense(out string id))
			//{
			//	LicenseWindow window = new LicenseWindow(id);
			//	window.Owner = this;
			//	window.ShowDialog();
			//	if ((bool)!window.DialogResult)
			//	{
			//		Environment.Exit(0);
			//	}
			//	else
			//	{
			//		window.Close();
			//	}
			//}

		}

		private void OnRadButtonClick(object sender, System.Windows.RoutedEventArgs e)
		{
			this.ShowSplashScreen();
		}

		private void ShowSplashScreen()
		{
			this.timer.Start();
			Mouse.OverrideCursor = Cursors.Wait;
			this.splashScreenDataContext = RadSplashScreenManager.SplashScreenDataContext as SplashScreenDataContext;
			if(splashScreenDataContext == null)
			{
				return;
			}
			this.splashScreenDataContext.ImagePath = "pack://application:,,,/images/SplashScreen.png";
			this.splashScreenDataContext.IsIndeterminate = false;
			this.splashScreenDataContext.Content = "Loading... 0%";
			this.splashScreenDataContext.Footer = "Copyright © 2024, 岱新（上海）电子科技有限公司";
			this.parentWindow.IsEnabled = false;
			if (this.parentWindow.WindowState != System.Windows.WindowState.Maximized)
			{
				var x = this.parentWindow.Left + this.parentWindow.ActualWidth / 2 - 260;
				var y = this.parentWindow.Top + this.parentWindow.ActualHeight / 2 - 160;
				RadSplashScreenManager.StartupPosition = new System.Windows.Point(x, y);
			}
			RadSplashScreenManager.Show();
		}

		private void CloseSplashScreen()
		{
			this.splashScreenDataContext.ProgressValue = 0;
			this.splashScreenDataContext.Content = string.Empty;
			this.timer.Stop();
			RadSplashScreenManager.Close();
			RadSplashScreenManager.StartupPosition = null;
			//this.parentWindow.CanMove = true;
			this.parentWindow.IsEnabled = true;
			Mouse.OverrideCursor = null;
		}

		private void UpdateProgress()
		{
			var progressValue = this.splashScreenDataContext.ProgressValue + random.NextDouble() * 3 + 2;
			this.splashScreenDataContext.ProgressValue = Math.Min(100, progressValue);
			this.splashScreenDataContext.Content = string.Format("加载中... {0:F0}%", this.splashScreenDataContext.ProgressValue);
			if (this.splashScreenDataContext.ProgressValue == 100)
			{
				this.splashScreenDataContext.Content = "完成";
				Thread.Sleep(350);
			}
		}

		private Dictionary<string, UserControl> controls = new Dictionary<string, UserControl>()
		{
			{ "测量", App.Current.Services.GetService<DaqView>() ?? throw new NullReferenceException()},
			{ "数据", App.Current.Services.GetService<DataManagerView>() ?? throw new NullReferenceException()},
			//{ "设置", App.Current.Services.GetService<DeviceConfigurationView>() ?? throw new NullReferenceException()},
			{ "设置", App.Current.Services.GetService<DeviceSettingsView>() ?? throw new NullReferenceException()},
		};


		private void SwitchContent(string name)
		{
            if (controls.TryGetValue(name, out UserControl? value))
            {
                contentControl.Content = value;
            }
        }

		public void SwitchTab(string name)
		{
			SwitchContent(name);
        }

		private void RadRibbonView_SelectionChanged(object sender, Telerik.Windows.Controls.RadSelectionChangedEventArgs e)
		{
			if (sender is RadRibbonView view)
			{
				if (view.SelectedItem is RadRibbonTab tab)
				{
					string header = tab.Tag.ToString();
					SwitchContent(header);
                }
			}
		}

        private void RadRibbonButton_Click(object sender, RoutedEventArgs e)
        {
            //         DeviceConfigurationView deviceConfigurationView = new();
            //deviceConfigurationView.Owner = this;
            //deviceConfigurationView.ShowDialog();
			var vm = App.Current.Services.GetService<DaqViewModel>();
			if (vm != null && vm.Daq.Status == DaqWorkStatus.Disconnected) 
			{
                SwitchContent("设备");
            }
			else
			{
				RadWindow.Alert(new DialogParameters { Header = "提示", Content = "数采正在运行中，禁止设置。" });
			}
		}

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
			AboutView aboutView = new();
			aboutView.Owner = this;
			aboutView.ShowDialog();
        }

        private void comboBoxTimeDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
			if(e.AddedItems != null && e.AddedItems.Count > 0)
			{
				if (e.AddedItems[0] is ChartTimeDivision division)
				{
					var view = App.Current.Services.GetService<DaqView>();
					if(view != null)
					{
						view.ChangeTimeDivision(division);
					}
				}
			}
        }

		private void ToggleLockYAxes(bool _lock)
		{
			var view = App.Current.Services.GetService<DaqView>();
			if (view == null) return;
			view.LockYAxes(_lock);
        }

        private void toggleSwitchButtonLockYAxes_Checked(object sender, RoutedEventArgs e)
        {
			ToggleLockYAxes(true);
        }

        private void toggleSwitchButtonLockYAxes_Unchecked(object sender, RoutedEventArgs e)
        {
            ToggleLockYAxes(false);
        }

        RadDesktopAlertManager manager = new RadDesktopAlertManager();
        public void Receive(DesktopAlertMessage message)
        {
			var alert = new RadDesktopAlert()
			{
				Header = message.Header,
				Content = message.Content,
				ShowDuration = message.Duration
			};
            manager.ShowAlert(alert);
        }

        private void RadComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private async void radRibbonWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
			var dialogService = App.Current.Services.GetService<IDialogService>();
			var dataManagerViewModel = App.Current.Services.GetService<DataManagerViewModel>();
			if(dialogService != null)
			{
				if(deviceService != null && deviceService.Status != DaqWorkStatus.Disconnected)
				{
                    await dialogService.ShowMessageAsync("警告", "数采正在运行，禁止退出。");
                    e.Cancel = true;
                }
				else if(dataManagerViewModel != null && dataManagerViewModel.IsExportingData)
				{
                    await dialogService.ShowMessageAsync("警告", "正在导出数据，禁止退出。");
                    e.Cancel = true;
                }
            }
        }

        private void backstageItemAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutView aboutView = new();
            aboutView.Owner = this;
            aboutView.ShowDialog();
        }
    }

    public class DesktopAlertMessage
	{
		public string? Header { get; set; }
		public string? Content { get; set; }
		public int Duration { get; set; }
        public DesktopAlertMessage(string header, string content, int duration = 3000)
        {
            Header = header;
			Content = content;
            Duration = duration;
        }
    }
}
